/**
 * 选医生
 */
$(function() {

	////初始化列表页面
	$(window).on("load", loadPageData);
 
	//跳转详情页【列表】
	$("#doctorDataBody").bind("click", ".picture", function(e) {
		enterDetail($(this).attr("v"));
	});
 
    $("#doctorDataBody").bind("click",".raios",function(e){
    	chooseDictor($(this).attr("v"),$(this).attr("fee"),$(this).attr("u"),$(this).attr("p"));
    });
 
    $(".choice-doctorSubmit").bind("click",submitOrder);
    
    

	/**
	 *请求服务器，加载分页数据
	 */
	var $pageNo = 1;

	var $pageSize = 5;

	/**
	 * 调用Model 检索接口
	 * @param {Object} _pageNo
	 * @param {Object} _pageSize
	 */
	function loadPageData( ) {
		var doctorObj = {};
		
		var params = {};
		params.pageNo=1;
		params.pageSize=5;
		params.isrecomm=1;//是否推荐
		
		choiceDoctorModule.queryList(params, function(callBack) {
			results = callBack;
			doctorObj.list = results.doctorList; 
		});
		utilModule.appendHtml("#doctorDataBody", "doctorDataDiv", doctorObj);

	}
 
    //选择医生
 	function chooseDictor(doctorid,fee,doctorName,hosptiName){
 		$("#showBtn").text(fee);
 		$("#payamount").val(fee);
 		$("#orderDetail").val(doctorName+"-图文咨询:"+hosptiName);
 		/*console.log(doctorName);*/
 	}

	//跳转详情
	function enterDetail(doctorid) {
		if(typeof(doctorid) =="undefined"){
			return false;
		}
		location.href = "../doctor/doctor-details.html?doctorid=" + doctorid+"&isdoctorinfo=1";
	}


	//提交支付
	function submitOrder(){
		
		var chooseObject=$("input[name='doctor']:checked");
		if(chooseObject.length<1){
		  mui.alert("请选择咨询医生信息","提示");
		  return false;
		}
		var payAmount=chooseObject.attr("fee");
		var $doctorId=chooseObject.attr("v");
		
		//提交咨询问题
		var orderObject={};
		var q_object=sessionStorage.getItem("q_index");
		if(q_object!=null){
		   orderObject=JSON.parse(q_object);	
		   orderObject.userid=USERID;
		   orderObject.doctorid=$doctorId;
		   orderObject.openid=OPENID;
		   orderObject.payAmount=$("#payamount").val();
		   orderObject.orderDetail=$("#orderDetail").val();
		}
		if($doctorId==0){
			var mask = mui.createMask();
			mask.show(); //显示遮罩
			
			  orderObject.questionerid=USERID;
			  choiceDoctorModule.submitFreeOrder(orderObject, function(callBack) {
				var data = callBack ;
				if(data.status) {
					mask.close(); //关闭遮罩		
					mui.alert("问题提交成功请等待医生回复","成功",function(){
						location.replace("../../index.html");
					});
								
				}else{
					mask.close(); //关闭遮罩
					mui.alert("问题提交成功请等待医生回复!","成功",function(){
						location.replace("../../index.html");
					});
					return false; 
				}
			  });
		}else{
			//1.查询未咨询订单，则直接跳转未完成咨询界面   2.新订单：a.免费 ，则直接跳转im  b.收费,则跳转支付
			var resultObject=queryUnfinishedOrder($doctorId);
			if(resultObject!=null){
			   var btnArray = ['否', '是'];
				mui.confirm('您有与该医生有一条未完成图文订单，去咨询？', '提示', btnArray, function(e) {
					if (e.index == 1) {
						 invokeIm(resultObject.id,$doctorId,resultObject.payamount);
					}
				})
			}else{
		      choiceDoctorModule.submitOrder(orderObject, function(callBack) {
				var data = callBack ;
				if(data != null) {
				   	 //如果免费咨询，则直接跳转聊天界面
			       var payAmount=$("#payamount").val();
			       if(payAmount==0.00 || payAmount==0){ 
			       	  invokeIm(data,$doctorId,0);
			       }else{
				     location.replace("../order/order-pay.html?orderid="+data+"&orderType=1")
			       }
				}
			  });
		 	}
		}

	}
	 
	 
	 
	/**
     * 查询未完成订单
     */
	function queryUnfinishedOrder($doctorid){
		
		var orderVo=null;
		var params={
			userid:USERID,
			doctorid:$doctorid
		}
		orderPayModule.queryUnfinishedOrder(params,function(callBack) {
			if(callBack != null) {
				if(utilModule.checkUndefined(callBack.id)!=""){
				   orderVo=callBack;
				}
			}
		});
		return orderVo;
	}
	
	/**
	 * 查询订单明细
	 * @param {Object} params
	 */
	function queryTextOrderDetail(params) {
		var params = {id: params};
		var result=null;
		orderPayModule.queryOrderDetail(params,
			function(callBack) {
				var orderInfo = callBack;
				if(orderInfo != null) {
					result=orderInfo;
				}
			});
		return result;
	}
	
	
	
	//跳转聊天im界面
	function invokeIm($orderid,$doctorid,$payamount) {
		var orderid = $orderid;
		var payStatus=parseFloat($payamount)==0.00?0:1;//免費咨詢	
		var doctorid=$doctorid;
		var params = {
			"doctorId": doctorid
		};
		
		/**查询订单明细 **/
		var orderInfo=queryTextOrderDetail($orderid);
		
		choiceDoctorModule.queryDetail(params, function(callBack) {
			var result = callBack;
			if(result != null) { 
				var doctorInfo = result.doctor;
				//doctor_user_20
				var doctorObject = {};
				doctorObject.doctorid = doctorInfo.id;
				var usernameIM =DOCTOR_IM_PREFFIX+doctorInfo.id;
				doctorObject.usernameIM = usernameIM;
				doctorObject.avatar = doctorInfo.avatar;
				doctorObject.realname = doctorInfo.realname;
				doctorObject.deptName = doctorInfo.deptName;
				utilModule.setStorage(usernameIM, JSON.stringify(doctorObject));
				
				//清空与该医生之前的聊天记录
				var chatList=utilModule.getStorage("chat_list");
				if(chatList!=null){
				   var  chatObject=JSON.parse(chatList);
				   
				   var rd_key=DOCTOR_IM_PREFFIX+doctorInfo.id;
				   delete chatObject[rd_key];
				  
				   var  $chatObject=JSON.stringify(chatObject);
				   
				   utilModule.setStorage("chat_list",$chatObject);
					
				}
				
				mui.toast("正在跳转咨询界面....");
				console.log("医生信息:" + utilModule.getStorage(usernameIM));
				
				//支付成功跳转im聊天界面 payStatus: 2:图文订单
				var questionbody=orderInfo.questionbody;
				var ext=orderInfo.membersex+":"+orderInfo.memberbirthday;
				var toImUrl="../inquiry/inquiry-service.html?usernameIM=" + usernameIM+"&orderid="+orderid+"&payStatus=2&doctorid="+doctorInfo.id;
				toImUrl+="&msg="+encodeURIComponent(questionbody)+"&ext="+ext;
				location.replace(toImUrl);
			}
		});
	}
	
	
});